package com.le.tester.imooc.ccmouse.loop;

import com.le.tester.imooc.ccmouse.common.Node;
import com.le.tester.imooc.ccmouse.recursion.LinkedListCreator;

import java.util.ArrayList;
import java.util.Arrays;

/**
 * 描述：删除链表中的元素（循环）
 */
public class LinkedListDeletor {

    public Node deleteIfEquals(Node head, int value) {

        while (head != null && head.getValue() == value) {
            head = head.getNext();
        }

        if (head == null) {
            return null;
        }

        Node prev = head;

        while (prev.getNext() != null) {
            if (prev.getNext().getValue() == value) {
                //delete
                prev.setNext(prev.getNext().getNext());
            } else {
                prev = prev.getNext();
            }
        }
        return head;
    }

    public static void main(String[] args) {
        LinkedListCreator linkedListCreator = new LinkedListCreator();
        LinkedListDeletor linkedListDeletor = new LinkedListDeletor();
        Node.printLinkedList(
                linkedListDeletor.deleteIfEquals(linkedListCreator.createLinkedList(Arrays.asList(1, 2, 3, 2, 5)), 2));

        Node.printLinkedList(
                linkedListDeletor.deleteIfEquals(linkedListCreator.createLinkedList(Arrays.asList(1, 2, 3, 2, 2)), 2));

        Node.printLinkedList(
                linkedListDeletor.deleteIfEquals(linkedListCreator.createLinkedList(Arrays.asList(1, 2, 3, 2, 2)), 1));

        Node.printLinkedList(
                linkedListDeletor.deleteIfEquals(linkedListCreator.createLinkedList(Arrays.asList(2, 2, 3, 2, 2)), 2));

        Node.printLinkedList(
                linkedListDeletor.deleteIfEquals(linkedListCreator.createLinkedList(Arrays.asList(2, 2, 2, 2, 2)), 2));

        Node.printLinkedList(
                linkedListDeletor.deleteIfEquals(linkedListCreator.createLinkedList(new ArrayList<>()), 2));
        System.out.println("============");

    }
}
